/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.worldjb.vk.auth;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import ru.worldjb.vk.ProfileFrame;
import ru.worldjb.vk.util.MainProps;

/**
 * Сцена авторизации
 * @author alex_xpert
 */
public class AuthScene extends Scene {
    final WebView wv = new WebView();
    final WebEngine we = wv.getEngine();

    public AuthScene(final Stage stage) {
        super(new StackPane(), 600, 500);
        we.getLoadWorker().stateProperty().addListener(
        new ChangeListener<Worker.State>() {
            public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) {
                if (newState == Worker.State.SUCCEEDED) {
                    stage.setTitle(we.getTitle());
                    if(we.getLocation().contains("access_token")) {
                        stage.close();
                        String token = we.getLocation().split("#access_token=")[1].split("&")[0];
                        MainProps.setProperty("access_token", token);
                        MainProps.save();
                        ProfileFrame pf = new ProfileFrame();
                        pf.setVisible(true);
                    }
                }
            }
        });
        we.load("http://oauth.vk.com/oauth/authorize"
                + "?client_id=4074314"
                + "&redirect_uri=https://oauth.vk.com/blank.html"
                + "&response_type=token"
                + "&scope=friends,messages,status,wall,offline"
                + "&v=5.8"
                + "&display=popup");
        
        ((StackPane) getRoot()).getChildren().add(wv);
    }
    
}
